package com.i.template.util;

import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.i.template.domain.UserDO;
import com.i.template.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @author lewis
 * @type class
 * @description
 * @since 2024/7/28
 */
@Slf4j
public class FileUtils {
    private final static  String AVATAR_PATH = "f:/images/avatar";
    private final static String KEY_PREFIX = "avatar-";
    private final static String MUSIC_PREFIX = "music-";
    private final static String MUSIC_PATH = "f:/images/music";
    private final static File FOLDER = new File(MUSIC_PATH);
    private final static File AVATAR_FOLDER = new File(AVATAR_PATH);
    public final static Pattern AUDIO_TYPE =  Pattern.compile("\\.(mp3|wav|ogg)$", Pattern.CASE_INSENSITIVE);
    //TODO: 未完成上传功能
    /**
     *  上传头像
     */
     public static String saveAvatar(Long userId,MultipartFile file) {
         if(file.isEmpty()){
             throw new BusinessException("文件不存在");
         }
         try (FastByteArrayOutputStream stream = new FastByteArrayOutputStream()) {
             if(!AVATAR_FOLDER.exists() && !AVATAR_FOLDER.mkdirs()) {
                 throw new BusinessException("创建文件夹失败!!!");
             }
             stream.write(file.getBytes());
             byte[] data = stream.toByteArray();
             String ext = FileTypeUtil.getType(file.getInputStream());
//                     Objects.requireNonNull(file.getOriginalFilename())
//                     .substring(file.getOriginalFilename().lastIndexOf(".") + 1);
//             String url = PATH + generateFileByTime() + generateFileBySecond() + "-" + generateUuid() + StrUtil.DOT + ext;
             String url = AVATAR_PATH + KEY_PREFIX + userId + "-" + UUID.randomUUID().toString(true) +  StrUtil.DOT + ext;
             FileUtil.writeBytes(data, url);
             return url;
         } catch (IOException e) {
             log.error("上传图片出现错误:{}",e.getMessage());
             throw new RuntimeException(e);
         }
     }
     public static String saveMusic(MultipartFile file) {

         if(file.isEmpty() && isAudioFile(file)){
             throw new BusinessException("文件不存在或文件格式不对");
         }
         try (FastByteArrayOutputStream stream = new FastByteArrayOutputStream()) {
             if(!FOLDER.exists() && !FOLDER.mkdirs()) {
                 throw new BusinessException("创建文件夹失败!!!");
             }
             stream.write(file.getBytes());
             byte[] data = stream.toByteArray();
             String ext = FileTypeUtil.getType(file.getInputStream());
//             String ext = Objects.requireNonNull(file.getOriginalFilename())
//                     .substring(file.getOriginalFilename().lastIndexOf(".") + 1);
             String url = MUSIC_PATH + MUSIC_PREFIX + "-" + UUID.randomUUID().toString(true) +  StrUtil.DOT + ext;
             FileUtil.writeBytes(data, url);
             return url;
         } catch (IOException e) {
             log.error("上传图片出现错误:{}",e.getMessage());
             throw new RuntimeException(e);
         }
     }
     public static Boolean isAudioFile(MultipartFile file) {
         if(StringUtils.isEmpty(file.getOriginalFilename())) {
             return false;
         }
         return BooleanUtil.isTrue(AUDIO_TYPE.matcher(file.getOriginalFilename()).matches());
     }
    public static String generateFileByTime() {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date()).replaceAll("-","/") + "/";
    }
    public static String generateFileBySecond() {
        DateFormat format = new SimpleDateFormat("HH-mm-ss");
        return format.format(new Date()).replaceAll("-","");
    }
    public static String generateUuid() {
        return UUID
                .randomUUID()
                .toString()
                .replaceAll("-","");
    }
}
